﻿using System;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using EasyComm.Hosting.Configuration;

namespace EasyComm
{
    [DataContract]
    public class ServiceContract : IDisposable
    {
        private object _proxy;

        internal Type ContractType { get; private set; }
        internal ServiceEndpoint Endpoint { get; set; }

        [DataMember]
        public string ContractName { get; private set; }

        [DataMember]
        public string AssemblyPath { get; private set; }

        [DataMember]
        public string AssemblyName { get; private set; }

        [DataMember]
        public Uri ListenUri { get; internal set; }

        public ServiceContract()
            : this(null, null)
        {
        }

        public ServiceContract(Type contractType, Uri listenUri)
        {
            ListenUri = listenUri;
            ContractName = contractType.FullName;
            ContractType = contractType;
            if (contractType != null)
            {
                AssemblyPath = contractType.Assembly.Location;
                AssemblyName = contractType.Assembly.FullName;
            }
        }

        public ServiceProxy<TContract> GetService<TContract>() where TContract : class
        {
            if (_proxy != null)
            {
                return _proxy as ServiceProxy<TContract>;
            }
            Binding binding = GenericConfiguration.GetMainBinding();
            EndpointAddress address = new EndpointAddress(ListenUri);
            _proxy = new ServiceProxy<TContract>(binding, address);
            return _proxy as ServiceProxy<TContract>;
        }

        public void Dispose()
        {
            if (_proxy != null)
            {
                (_proxy as IDisposable).Dispose();
            }
        }
    }
}
